# -*- coding: utf-8 -*-
#__author__ = '风中的思绪'

from openerp.osv import orm
import datetime



_search_original = orm.BaseModel._search


def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
    start = datetime.datetime.now()
    result = _search_original(self, cr, user, args, offset, limit, order, context, count, access_rights_uid)
    duration = datetime.datetime.now() - start
    if context:  # make sure context is ready
        sql_trace = context.get("sql_trace", False)  # default no trace
        sql_module = context.get("sql_module", 'Empty')   # in case global context not ready
        sql_model = context.get("sql_model", 'Empty')
        if sql_module == 'Empty':
            check_module = False
        elif not sql_module:    # leave module emtpy to trace all modules
            check_module = True
        else:
            check_module = self._module in sql_module
        if sql_model == 'Empty':
            check_model = False
        elif not sql_model:  # leave model empty to trace all models
            check_model = True
        else:
            check_model = self._name in sql_model
        if sql_trace and check_module and check_model:
            query = self._where_calc(cr, user, args, context=context)
            self._apply_ir_rules(cr, user, query, 'read', context=context)
            order_by = self._generate_order_by(order, query)
            from_clause, where_clause, where_clause_params = query.get_sql()
            where_str = where_clause and (" WHERE %s" % where_clause) or ''
            limit_str = limit and ' limit %d' % limit or ''
            offset_str = offset and ' offset %d' % offset or ''
            query_str = 'SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str
            cr.execute("""INSERT INTO sqltrace (module,model,statement,user_id,sql,parameters, result, duration, date_update)
                                VALUES (%s,%s, %s, %s,%s, %s, %s ,%s, (now() at time zone 'UTC'))""",
                                (self._module, self._name, 'select', user, query_str, reduce(lambda x, y: str(x)+' ,'+str(y),
                                where_clause_params or ['']), str(result or ['']), duration.seconds))
    return result
orm.BaseModel._search = _search